//
//  StatisticsManager.m
//  FH2go
//
//  Created by Hannes Feichtl on 12.06.13.
//  Copyright (c) 2013 Hannes Feichtl. All rights reserved.
//

#import "StatisticsManager.h"
#import "Statistics.h"
#import "TouchXML.h"
#import "SettingsManager.h"


@implementation StatisticsManager

@synthesize queue = _queue;

- (id)init {
    self = [super init];
    if (self) {
        _queue = [[NSOperationQueue alloc] init];
        
        // A maximum of concurrent operations
        [_queue setMaxConcurrentOperationCount:4];
    }
    return self;
}

- (void)fetchStatistics:(void(^)(Statistics *statistics,NSError *error)) completion fromID: (NSString*) examid {
    
    NSString *username = [[SettingsManager sharedInstance] username];
    NSString *password = [[SettingsManager sharedInstance] password];
    // Get username and password from settings manager
    if (!username || !password || username.length==0 || password.length==0) {
        // create error
        NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
        [errorDetail setValue:@"Invalid user credentials. Go to settings and enter your credentials." forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"None" code:100 userInfo:errorDetail];
        // run completion block with error
        completion(nil,error);
        // No need to request server when no username or password. Return method!
        return;
    }
    
    // create URL string with username and password included
    NSString *requestString = [NSString stringWithFormat:@"https://ws.fh-joanneum.at/getstatistics.php?u=%@&p=%@&id=%@&k=LOvkZCPesk",username,password,examid];
       
    // creates the request from a URL
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestString] cachePolicy:0 timeoutInterval:30];
    
    /*
     creates an asynchronous request using the request variable created above
     also includes a block which returns the content of the marks if no error occured, otherwise returns an error
     */
    
    [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler:^(NSURLResponse *response, NSData *date, NSError *error) {
        
        //If the request returned an error
        if (error) {
             NSLog(@"Error: %@",error);
            /* executes this again on the main thread */
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(nil, error);
                
            });
        } else {
           
            // Array to hold the returned data
            Statistics *statistics;
            
            // Create a XMLDocument from the returned data
            CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithData:date encoding:NSUTF8StringEncoding options:0 error:nil];
                        
            // Checks if the request was succesfull by looking at the Status returned
            if(![[[xmlDoc nodeForXPath:@"//Status" error:nil] stringValue] isEqualToString:@"OK"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // Create error
                    NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
                    [errorDetail setValue:@"Something went wrong. Please check your credentials in settings." forKey:NSLocalizedDescriptionKey];
                    NSError *error = [NSError errorWithDomain:@"None" code:100 userInfo:errorDetail];
                    // run completion block with error
                    completion(nil,error);
                });
                // No need to continue parsing when server returns bad status. Return method!
                return;
            }
            
            // Parses the XML into objects
            NSArray *responseNodes = [xmlDoc nodesForXPath:@"//Statistic" error:nil];
            for (CXMLElement *node in responseNodes) {
                NSMutableDictionary *c = [[NSMutableDictionary alloc] init];
                                
                for (CXMLNode *childNode in [node children]) {
                   
                    [c setObject:[childNode stringValue] forKey:[childNode name]];
                }
                
                statistics = [[Statistics alloc] initWithDict:c];
            }
            
            /*
             will be executed on the main thread again
             dispatch_get_main_queue() -> C function will return the main queue
             */
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(statistics, nil);
                
            });
        }
    }];
}


@end
